import { debounce } from "es-toolkit/function";
import { toast } from "sonner";

/**
 * @description previewFitScale 画布自适应
 * @param {number} width ui 设计稿宽度
 * @param {number} height ui 设计稿高度
 * @param {HTMLElement} scaleDom 缩放的元素
 * @param {(scale: { width: number; height: number }) => void} callback
 * @author 花东红
 * @time 2025/8/21
 */
export const previewFitScale = (width: number, height: number, scaleDom: HTMLElement | null, callback?: (scale: { width: number; height: number }) => void) => {
  // 画布尺寸（px）
  const baseWidth = width;
  const baseHeight = height;

  // 默认缩放值
  const scale = {
    width: 1,
    height: 1
  };

  // 需保持的比例
  const baseProportion = Number.parseFloat((baseWidth / baseHeight).toFixed(5));

  // 动态设置缩放比例
  const calcRate = () => {
    // 当前屏幕宽高比
    const currentRate = Number.parseFloat((window.innerWidth / window.innerHeight).toFixed(5));
    if (scaleDom) {
      if (currentRate > baseProportion) {
        // 表示更宽
        scale.width = Number.parseFloat(((window.innerHeight * baseProportion) / baseWidth).toFixed(5));
        scale.height = Number.parseFloat((window.innerHeight / baseHeight).toFixed(5));
        scaleDom.style.transform = `scale(${scale.width}, ${scale.height})`;
        scaleDom.style.transition = "all 0.2s";
      } else {
        // 表示更高
        scale.height = Number.parseFloat((window.innerWidth / baseProportion / baseHeight).toFixed(5));
        scale.width = Number.parseFloat((window.innerWidth / baseWidth).toFixed(5));
        scaleDom.style.transform = `scale(${scale.width}, ${scale.height})`;
        scaleDom.style.transition = "all 0.2s";
      }
      if (callback) callback(scale);
    }
  };

  const resize = debounce(() => {
    calcRate();
  }, 200);

  // 改变窗口大小重新绘制
  const windowResize = () => {
    window.addEventListener("resize", resize);
  };

  // 卸载监听
  const unWindowResize = () => {
    window.removeEventListener("resize", resize);
  };

  // 初始化画布尺寸
  const initializeResize = () => {
    calcRate();
    windowResize();
  };

  return {
    calcRate,
    windowResize,
    unWindowResize,
    initializeResize
  };
};

/**
 * @description checkStatus 校验网络请求状态码
 * @param {number} status
 * @author 花东红
 * @time 2025/8/7
 */
export const checkStatus = (status: number) => {
  const codeMap: Record<string, string> = {
    400: "请求失败！请您稍后重试",
    403: "当前账号无权限访问！",
    404: "你所访问的接口不存在！",
    405: "请求方式错误，请您稍后重试",
    408: "请求超时，请您稍后重试",
    500: "服务异常，请您稍后重试",
    502: "网关错误，请您稍后重试",
    503: "服务不可用，请您稍后重试",
    504: "网关超时，请您稍后重试"
  };
  if (codeMap[status]) return toast.error(codeMap[status]);
  toast.error("请求失败，请您稍后重试");
};
